/**
 * 
 */
package pers.vic.test.json.jackson;

import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *  @description: 
 *  @author Vic.xu
 *  @date: 2020年9月14日下午2:23:44
 */
public class CustomerDateFormat extends DateFormat {
	 
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private DateFormat dateFormat;
 
	private SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	public CustomerDateFormat() {
	}
 
	public CustomerDateFormat(DateFormat dateFormat) {
		this.dateFormat = dateFormat;
	}
 
	@Override
	public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
		if(date instanceof java.sql.Timestamp) {
			long time = date == null ? 0L : date.getTime();
			return new StringBuffer(time + "");
		}
		return dateFormat.format(date, toAppendTo, fieldPosition);
	}
 
	@Override
	public Date parse(String source, ParsePosition pos) {
 
		Date date = null;
 
		try {
 
			date = format1.parse(source, pos);
		} catch (Exception e) {
 
			date = dateFormat.parse(source, pos);
		}
 
		return date;
	}
 
	// 主要还是装饰这个方法
	@Override
	public Date parse(String source) throws ParseException {
 
		Date date = null;
 
		try {
			
			// 先按我的规则来
			date = format1.parse(source);
		} catch (Exception e) {
 
			// 不行，那就按原先的规则吧
			date = dateFormat.parse(source);
		}
 
		return date;
	}
 
	// 这里装饰clone方法的原因是因为clone方法在jackson中也有用到
	@Override
	public Object clone() {
		Object format = dateFormat.clone();
		return new CustomerDateFormat((DateFormat) format);
	}
}
